﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corp." file="ParallelOperation.cs">
//   All rights reserved. See License.txt in the project root for license information.
// </copyright>
// 
// --------------------------------------------------------------------------------------------------------------------
namespace CloudBlitz.DeploymentManager.DeploymentWorkflow
{
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;

    public class ParallelOperation : CompositeOperationBase
    {
        public ParallelOperation(IEnumerable<IDeploymentOperation> operations) : base(operations)
        {
        }

        protected override OperationResult ExecuteOverride(DeploymentContext context)
        {
            var results = new ConcurrentBag<OperationResult>();

            Parallel.ForEach(this.operations, operation =>
            {
                try
                {
                    results.Add(operation.Execute(context));
                }
                catch (Exception e)
                {
                    results.Add(ExceptionHelper.HandleException(e));
                }
            });

            if (results.Any(x => x.Status == DeploymentOperationStatus.Failed))
            {
                return results.First(x => x.Status == DeploymentOperationStatus.Failed);
            }

            return OperationResult.Success;
        }
    }
}